<template>
  <el-form
      ref="ruleFormRef"
      :model="formData"
      label-width="auto"
      style="max-width: 800px"
      status-icon
  >
    <el-form-item label="设备名称" :rules="[{required: true,message: '请输入设备名称',trigger: 'blur'}]" prop="name">
      <el-input v-model="formData.name"/>
    </el-form-item>
    <el-form-item label="设备密码" :rules="[{required: true,message: '请输入设备密码',trigger: 'blur'}]" prop="password">
      <el-input v-model="formData.password"/>
    </el-form-item>
    <el-form-item label="设备IP" :rules="[{required: true,message: '请输入设备IP',trigger: 'blur'}]" prop="ip">
      <el-input v-model="formData.ip"/>
    </el-form-item>
    <el-form-item label="设备端口" :rules="[{required: true,message: '请输入设备端口',trigger: 'blur'}]" prop="port">
      <el-input v-model="formData.port"/>
    </el-form-item>
    <el-form-item label="设备通道" :rules="[{required: true,message: '请输入设备通道',trigger: 'blur'}]" prop="channel">
      <el-input v-model="formData.channel"/>
    </el-form-item>
    <el-form-item prop="video" label="开启录像" :rules="[{required: true,message: '请选择性别',trigger: 'blur'}]">
      <el-radio-group v-model="formData.video">
        <el-radio :value="1">是</el-radio>
        <el-radio :value="0">否</el-radio>
      </el-radio-group>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submit(ruleFormRef)">
        提交
      </el-button>
      <el-button type="primary" @click="router.back()">
        取消
      </el-button>
    </el-form-item>
  </el-form>
</template>

<script setup name="DeviceEditView" lang="ts">
import {onMounted, ref} from "vue";
import Device from "@/model/Device";
import {useRoute, useRouter} from "vue-router";
import DeviceApi from "@/axios/DeviceApi";
import {ElMessage, type FormInstance} from "element-plus";

const ruleFormRef = ref<FormInstance>()
const formData = ref<Device>(new Device())
const route = useRoute()
const router = useRouter()
onMounted(() => {
  if (route.query.id) {
    const id = parseInt(route.query.id as string);
    DeviceApi.get(id)
        .then(resp => {
          Object.assign(formData.value, resp.data)
        })
  }
})

const submit = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate((valid: boolean) => {
    if (valid) {
      if (route.query.id) {
        const id = parseInt(route.query.id as string);
        DeviceApi.update(id, formData.value)
            .then(() => {
              ElMessage.success("修改成功")
              router.back()
            })
      } else {
        DeviceApi.save(formData.value)
            .then(() => {
              ElMessage.success("保存成功")
              router.back()
            })
      }
    }
  })
}
</script>


<style lang="less" scoped>
</style>